package com.wry.juc;



import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * <h1>  </h1>
 *
 * @author wry
 * @since 2025.04.02
 */
public class NodeTest<E> {
    NodeTest<E> head = null;
    NodeTest<E> tail = null;

    E e;
    NodeTest<E> prev;
    NodeTest<E> next;

    public NodeTest() {

    }
    public NodeTest(E e) {
        this.e = e;
    }

    public void add(E e) {
        NodeTest<E> newNode = new NodeTest<>(e);
        NodeTest<E> currentTailNode = tail;
        if (currentTailNode == null) {
            // 如果链表为空，头尾都指向新节点
            head = newNode;
            tail = newNode;
        } else {
            currentTailNode.next = newNode;
            newNode.prev = currentTailNode;
            tail = newNode;
        }
    }

    @Override
    public String toString() {
        NodeTest<E> e = head;
        List<E> eList = new ArrayList<>();
        while (e != null) {
            eList.add(e.e);
            e = e.next;
        }
        return eList.toString();
    }

    public void remove(E e) {
        if (tail == null) {
            throw new RuntimeException("没有元素可移除");
        }
        NodeTest<E> h = head;
        while (h != null) {
            if (h.e.equals(e)) {
                if (h.prev != null) {
                    h.prev.next = h.next;
                } else {
                    // h是头节点
                    head = h.next;
                    System.out.println("删除头节点-> "+ h.e);
                }
                if (h.next != null) {
                    h.next.prev = h.prev;
                } else {
                    // h是尾节点
                    tail = h.prev;
                    System.out.println("删除尾节点-> "+ h.e);
                }
                break;
            }
            h = h.next;
            if (h == null) {
                System.out.println("不存在此元素 -> " + e);
            }
        }


    }


    public void append(E e) {
        NodeTest<E> newNode = new NodeTest<>(e);
        NodeTest<E> currentHeadNode = head;
        if (currentHeadNode == null) {
            // 如果链表为空，头尾都指向新节点
            head = newNode;
            tail = newNode;
        } else {
            currentHeadNode.prev = newNode;
            newNode.next = currentHeadNode;
            head = newNode;
        }
    }

    public static void main(String[] args) {
        LinkedList<String> linkedList = new LinkedList<>();
        linkedList.add("1");
        linkedList.add("3");
        linkedList.add("4");
        System.out.println(linkedList);
    }
}
